<template>
    <!-- 添加分账方及添加分账接收方按钮弹窗 -->
    <div>
        <div @click="openDialogHandler">
            <slot>
                <el-tooltip
                    :disabled="(selectedDivisionNum < 20 && moduleType == 2) || moduleType == 1"
                    placement="top"
                    content="最多选择20个分账接收方">
                    <el-button
                        :disabled="selectedDivisionNum >= 20 || (!splitOpenNo && moduleType == 2)"
                        type="primary"
                        >{{ name }}</el-button
                    >
                </el-tooltip>
            </slot>
        </div>
        <el-dialog class="select-account-dialog" align-center :title="props.title" v-model="visible" width="800px">
            <div class="select-account-dialog-body">
                <div class="select-account-dialog-search">
                    <el-input v-model="form.keywords" placeholder="请输入商户名称/简称/统一社会信用代码" />
                    <div>
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button @click="resetHandler">清空</el-button>
                    </div>
                </div>
                <div class="select-account-dialog-table">
                    <el-checkbox-group v-model="checkList">
                        <el-table v-loading="loading" :data="tableList" :height="450">
                            <el-table-column width="55">
                                <template #default="{ row }">
                                    <el-tooltip
                                        :disabled="row.account_status !== 1 && !row.is_bill"
                                        placement="top"
                                        :content="row.is_bill ? `当前商户已是分账方` : `当前商户的账户尚未开通`">
                                        <el-checkbox
                                            :disabled="row.account_status == 1 || row.is_bill"
                                            :label="row.id"
                                            @change="val => checkDataChangeHandler(val, row)">
                                            <!-- 别去掉这个div -->
                                            <div></div>
                                        </el-checkbox>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column
                                v-for="{ prop, ...rest } in tableColumns"
                                :key="prop"
                                :prop="prop"
                                v-bind="rest">
                                <template #default="{ row }">
                                    <template v-if="prop === 'corp_name'">
                                        <div class="corp-name">
                                            <div class="corp-name-main">
                                                <ZwTooltip :content="row.corp_name" :line="2" />
                                            </div>
                                            <div class="corp-name-sub" v-if="row.corp_unified_social_credit_code">
                                                <ZwTooltip :content="row.corp_unified_social_credit_code" />
                                            </div>
                                        </div>
                                    </template>
                                    <template v-if="prop === 'status_name'">
                                        <span
                                            class="custom-status-point"
                                            :style="{ '--status-bgcolor': StatusColorOption[row.status] }">
                                            {{ row.status_name }}
                                        </span>
                                    </template>
                                </template>
                            </el-table-column>
                            <template #empty>
                                <div class="table-empty table-empty-min">
                                    <img
                                        src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1697683499137ngcb4fpdwjr9ijb4.png" />
                                    <div>暂无数据</div>
                                </div>
                            </template>
                        </el-table>
                    </el-checkbox-group>
                    <Pagination
                        :total="totalCount"
                        :page-size="form.page_size"
                        :current-page="form.page"
                        @sizeChange="changeSizeHandler"
                        @pageChange="changePageHandler"></Pagination>
                </div>
            </div>
            <template #footer>
                <div class="custom-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button
                        type="primary"
                        v-if="divisionType == 'API'"
                        :disabled="!checkList?.length"
                        @click="handleAPISetConfirm"
                        >确认</el-button
                    >
                    <el-button type="primary" v-else :disabled="!checkList?.length" @click="handleNext"
                        >下一步</el-button
                    >
                </div>
            </template>
        </el-dialog>
        <SetAccountPeriod
            v-model="showAccountPeriod"
            :selected="selectedList"
            @handle-confirm="handleSetConfirm"
            @handle-prev="handlePrev"></SetAccountPeriod>
        <AcceptInfo
            v-model="showAccountRadio"
            :tableData="selectedList"
            :splitOpenId="splitOpenId"
            type="add"
            @handle-confirm="handleSetConfirm"
            @handle-prev="handlePrev"></AcceptInfo>
    </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import Pagination from '@/components/Pagination.vue';
import AcceptInfo from './../AcceptInfo.vue';
import SetAccountPeriod from './SetAccountPeriod.vue';
import request from '@/request/index';
import ZwTooltip from '@/components/ZwTooltip.vue';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-close']); //  Boolean => false:取消弹窗；true:提交后关闭
const props = defineProps({
    name: {
        type: String,
        default: '选择'
    },
    title: {
        type: String,
        default: '选择分账方'
    },
    // 操作模块 1-分账方选择弹窗列表 2-分账接收方选择弹窗列表
    moduleType: {
        type: Number,
        default: 1
    },
    // 分账方开户号【handle_module=2时必传】
    splitOpenNo: {
        type: String,
        default: ''
    },
    //  分账方Id【handle_module=2时必传】
    splitOpenId: {
        type: String,
        default: ''
    },
    // 分账方式【handle_module=2且分账方式api分账时需要】
    divisionType: {
        type: String,
        default: ''
    },
    // 选择的分账接收方数量【handle_module=2时需要】
    selectedDivisionNum: {
        type: Number,
        default: 0
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
const visible = ref(false);

/**
 * 监听显示隐藏，每次关闭时取消勾选
 */
watch(visible, () => {
    if (!visible.value) {
        checkList.value = [];
        selectTableList.value = [];
    } else {
        searchHandler();
    }
});

/**
 * 勾选的数据
 */
const checkList = ref([]);

/**
 * 取消操作
 */
const handleCancel = () => {
    checkList.value.length = 0;
    visible.value = false;
    emit('handle-close', false);
};

/**
 * 下一步
 */
const handleNext = () => {
    if (!checkList.value.length) {
        ElMessage.warning('请选择分账方');
        return;
    }
    if (props.moduleType == 2) {
        if (props.selectedDivisionNum + checkList.value.length > 20) {
            ElMessage.warning('最多选择20个分账接收方');
            return;
        }
        showAccountRadio.value = true;
    } else {
        showAccountPeriod.value = true;
    }
    selectedList.value = [];
    checkList.value.forEach(x => {
        const a = selectTableList.value.find(e => e.id == x);
        if (a) {
            selectedList.value.push(a);
        }
    });
    visible.value = false;
};

const openDialogHandler = () => {
    visible.value = true;
    initData();
};

// 初始化数据
const initData = () => {
    form.keywords = '';
    form.page_size = 10;
    form.page = 1
}

/* ---------------------------------- 控制弹窗 end ---------------------------------- */

/* ----------------------------列表搜索-start---------------------------- */

const form = reactive({
    keywords: '',
    page_size: 10,
    page: 1
});

const tableList = reactive([]);
const totalCount = ref(0);

let formClone = reactive({});

// 进度状态颜色
const StatusColorOption = {
    10: '#EAEAEA', // 草稿中
    20: '#FF6B00', // 开户中
    30: '#60B900' // 开户完成
};

/**
 * 列表配置项
 */
const tableColumns = [
    { label: '商户信息', prop: 'corp_name', minWidth: '280' },
    { label: '主体类型', prop: 'corp_main_type_name', minWidth: '170' },
    { label: '账户状态', prop: 'status_name', minWidth: '140' }
];

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    Object.assign(formClone, cloneDeep(form));
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.page_size = perPage;
    Object.assign(formClone, cloneDeep(form));
    queryListHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    form.keywords = null;
    searchHandler();
};

/**
 * 分页查询
 */
const loading = ref(false);
const queryListHandler = async () => {
    loading.value = true;
    const para = Object.assign(formClone, {
        handle_module: props.moduleType,
        split_open_no: props.splitOpenNo,
        status: 30
    });
    const { data } = await request('accountManageList', para);
    loading.value = false;
    tableList.length = 0;
    tableList.push(...(data?.data || []));
    totalCount.value = data?.total || 0;
};

/* ----------------------------列表搜索-end---------------------------- */

/* ----------------------------设置分账方式（倍率）-start---------------------------- */
/**
 * 设置分账方式显示隐藏
 */
const showAccountPeriod = ref(false);

const showAccountRadio = ref(false);

/**
 * 勾选后确认的数据
 */
const selectedList = ref([]);

/**
 * 勾选的数据(会含有取消的)
 */
const selectTableList = ref([]);
const checkDataChangeHandler = (value, row) => {
    if (checkList.value.includes(row.id) && value) {
        selectTableList.value.push(row);
    } else if (!value) {
        selectTableList.value = selectTableList.value.filter(x => x.id !== row.id);
    }
};

/**
 * 上一步操作
 */
const handlePrev = val => {
    showAccountPeriod.value = false;
    showAccountRadio.value = false;
    visible.value = true;
    checkList.value = Array.from(val, x => x.id);
    selectTableList.value = val;
};
/**
 * 设置后的确认
 */
const handleSetConfirm = value => {
    // 关闭弹窗
    if (!value) {
        emit('handle-close', false);
    } else {
        // 确认提交
        showAccountPeriod.value = false;
        showAccountRadio.value = false;
        emit('handle-close', true);
    }
};
/**
 * 添加分账接收方（分账方式为API分账时不需要设置比例）
 */
const handleAPISetConfirm = async () => {
    const para = {
        split_account_id: props.splitOpenId,
        split_account_receiver: []
    };
    checkList.value.forEach(x => {
        const a = selectTableList.value.find(e => e.id == x);
        para.split_account_receiver.push({
            open_no: a.open_no,
            ratio: ''
        });
    });
    await request('addReceiverSplitAccountServ', para);
    visible.value = false;
    emit('handle-close', true);
};
/* ----------------------------设置分账方式（倍率）-end---------------------------- */
</script>
<style lang="scss" scoped>
.select-account-dialog-search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
        width: 300px;
    }
}

.select-account-dialog-table {
    margin-top: 18px;
}

.corp-name-main {
    font-size: 14px;
    font-weight: 400;
    color: #33302d;
    margin-bottom: 8px;
    padding: 0 5px;
}

.corp-name-sub {
    font-size: 14px;
    font-weight: 400;
    color: #999999;
    line-height: 14px;
    padding: 0 5px;
}

.custom-status-point {
    display: flex;
    align-items: center;
    line-height: normal;

    &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        margin-right: 8px;
        background-color: var(--status-bgcolor);
        border-radius: 4px;
    }

    .custom-status-icon {
        cursor: pointer;
        width: 16px;
        height: 16px;
        margin-left: 6px;
    }
}
.table-empty-min {
    min-height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    img {
        width: 50%;
        height: 50%;
    }
}
</style>
